package tech.yixiyun.framework.kuafu.db.sql.handler;

import org.apache.commons.dbutils.ResultSetHandler;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 插入数据后，如果有自增列，根据Field对自增结果做处理
 */
public class IdColumnHandler implements ResultSetHandler {
    private Field idField; //id字段
    private Object instance;
    public IdColumnHandler(Field idField, Object instance) {
        this.idField = idField;
        this.instance = instance;
    }
    @Override
    public Object handle(ResultSet rs) throws SQLException {
        if (idField == null || rs.next() == false) return null;
        Object v = rs.getObject(1);

        return handle(instance, idField, v);

    }

    public static Object handle(Object instance, Field idField, Object value) {
        Object result = null;
        if (instance != null && idField != null && value != null) {
            if (idField.getType() == int.class || idField.getType() == Integer.class) {
                result = Integer.valueOf(value.toString());
            } else if (idField.getType() == long.class || idField.getType() == Long.class) {
                result = Long.valueOf(value.toString());
            }
        }

        if (result != null) {
            try {
                idField.set(instance, result);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

}
